package com.garlic.face.jlf.ui;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.garlic.face.jlf.App;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.ServiceInterface;
import com.garlic.face.jlf.transaction.constances.JLFConstant;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by shiyanqi on 18/8/20.
 */

public class CashierLoginActivity extends BaseActivity {

    private Button OKBtn;
    private Button loginClose;
    private EditText cashierEdt;
    private EditText cashierPwdEdt;
    private InputMethodManager inputMethodManager; // 软键盘
    private LinearLayout cashierLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ceshier_login);
        loginClose = findViewById(R.id.login_close);
        OKBtn = findViewById(R.id.cashier_OK_button);
        cashierEdt = findViewById(R.id.cashier);
        cashierPwdEdt = findViewById(R.id.cashierPwd);
        cashierLayout = findViewById(R.id.cashier_layout);
        /*cashierEdt.setText("1018");
		cashierPwd.setText("1234");*/
        inputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));

        OKBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty((String) Tools.getPref(App.CONFIG_INFO, App.POS_IP, ""))) {
                    ToastUtils.toastShow("请先配置设备信息", ToastUtils.ERROR);
                    finish();
                    return;
                }
                if(MainActivity.getSocketService().isSocketNull()){
                    ToastUtils.toastShow("服务器未连接,请检查POS机！", ToastUtils.ERROR);
                    return;
                }
                getStateInfo();
            }
        });
        loginClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        cashierLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideSoftInput();
            }
        });
        EventBus.getDefault().register(this);

    }

    public void getStateInfo() {
        showProgress();
        ServiceInterface.getInstance().stateLogin();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveResponse(JSONObject jsonObject) {
        LogUtils.d("receive msg" + jsonObject.toString(), true);
        try {
            String interfaceType = jsonObject.getString("INTERFACETYPE");
            if (interfaceType.equals(JLFConstant.TAG_STATE_RESPONSE)) {
                //状态
                String retflag = jsonObject.getString("retflag");
                String stateMsg = jsonObject.getString("retmsg");
                if (retflag.equals("0")) {
                    if (stateMsg.equals(JLFConstant.POS_CLOSE)) {
                        //需要登录
                        ServiceInterface.getInstance().cashierLogin(cashierEdt.getText().toString().trim(), cashierPwdEdt.getText().toString().trim());
                    } else if (stateMsg.equals(JLFConstant.POS_OPEN)) {
                        hideProgress();
                        hideSoftInput();
                        //已经登录，直接开始交易即可
                        ToastUtils.toastShow("已经登录", ToastUtils.SUCCESS);
                        LogUtils.d("receive msg" + jsonObject.toString(), false);
                        Means.getInstance().setLoginServer(true);
                        finish();
                    } else if (stateMsg.equals(JLFConstant.POS_BETWEEN_ITEM)) {
                        //Request is not accepted
                        //有商品，需要输入授权，删除整单
						hideSoftInput();
                        // TODO: 2018/7/30 这里要判断viodsIntervention是否为0
                        //取消单品不需要送supervisor
                        ServiceInterface.getInstance().cancelTrade("", "");
                    } else if (stateMsg.equals(JLFConstant.POS_SUBTOTAL)) {
                        //有商品，需要输入授权，删除整单
						hideSoftInput();
                        // TODO: 2018/7/30 这里要判断viodsIntervention是否为0
                        //取消单品不需要送supervisor
                        ServiceInterface.getInstance().cancelTrade("", "");
                    } else if (stateMsg.equals(JLFConstant.POS_PARTIAL_PAYMENT)) {
                        hideProgress();
                        //需要重启POS
                        ToastUtils.toastShow("部分支付   需要重启POS", ToastUtils.ERROR);
                    } else {
                        hideProgress();
                        ToastUtils.toastShow("POS状态异常   需要重启POS", ToastUtils.ERROR);
                    }
                } else {
                    hideProgress();
                    //获取状态失败
                    ToastUtils.toastShow("获取POS状态失败   需要重启POS", ToastUtils.ERROR);
                }
            } else if (interfaceType.equals(JLFConstant.TAG_LOGIN_RESPONSE)) {
                String retflag = jsonObject.getString("retflag");
                String retmsg = jsonObject.getString("retmsg");
                hideProgress();
                if (retflag.equals("0")) {
                    //登录成功
					hideSoftInput();
                    String cashier = jsonObject.getString("cashier");
                    String cashierPwd = cashierPwdEdt.getText().toString().trim();
                    String voidsIntervention = jsonObject.getString("voidsIntervention");
                    Means.getInstance().setVoidsIntervention(voidsIntervention);
                    Means.getInstance().setLoginCashier(cashier);
                    Means.getInstance().setLoginCashierPwd(cashierPwd);
                    Means.getInstance().setLoginServer(true);
                    Tools.putPref(App.CONFIG_INFO, App.CASH_NAME, cashier);
                    Tools.putPref(App.CONFIG_INFO, App.CASH_PWD, cashierPwd);
                    LogUtils.d("登录成功" + Means.getInstance().toString(), true);
                    ToastUtils.toastShow("登录成功！", ToastUtils.SUCCESS);
                    finish();
                } else {
                    //登录失败
                    //ToastUtil.getInstance().showToast(getActivity(), "收银员登录失败：" + retmsg, Toast.LENGTH_LONG);
                    LogUtils.e("登录失败" + retmsg);
                    ToastUtils.toastShow("收银员登录异常" + retmsg, ToastUtils.ERROR);
                }
            } else if (interfaceType.equals(JLFConstant.TAG_CANCELTRADE_RESPONSE)) {
                String retflag = jsonObject.getString("retflag");
                String retmsg = jsonObject.getString("retmsg");
                hideProgress();
                if (retflag.equals("0")) {
                    Tools.clearTrade();
                    ToastUtils.toastShow("登录成功！", ToastUtils.SUCCESS);
                    Means.getInstance().setLoginServer(true);
                } else {
                    LogUtils.e(retmsg);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftInput(){
        if (inputMethodManager != null) {
            // 参数1：当前viewTree任意一个view的windowToken     参数2：没要求0即可
            inputMethodManager.hideSoftInputFromWindow(cashierEdt.getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
